package com.websocket.endpoint;

import com.websocket.mapper.ChatHistoryMapper;
import com.websocket.model.ChatHistory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

@ServerEndpoint("/chat")
public class ChatEndpoint {
    private static ChatHistoryMapper mapper;

    private static ApplicationContext applicationContext;
    @Autowired
    public void setApplicationContext(ApplicationContext context) {
        applicationContext = context;
        mapper = applicationContext.getBean(ChatHistoryMapper.class);
    }

    @OnOpen
    public void onOpen(Session session) {
        System.out.println("连接建立: "  + session.getId());
    }

    @OnClose
    public void onClose(Session session) {
        System.out.println("连接关闭: " + session.getId());
        // 添加清理逻辑
    }

    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace(); // 添加错误日志记录
    }

    @Autowired
    public void setMapper(ChatHistoryMapper mapper) {
        if (ChatEndpoint.mapper == null)
        ChatEndpoint.mapper = mapper;
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        ChatHistory record = new ChatHistory();
        record.setContent(message);

        try {
            if (mapper != null) {
                System.out.println("正在存储消息：" + message);
                // 修复：使用MyBatis的insert方法后不需要再手动调用
                mapper.insert(record);
                // 移除重复的insert调用
                // mapper.insert(record); // 删除这行

                // 添加事务提交（根据实际配置）
                session.getBasicRemote().sendText("消息已保存");
            }
        } catch (Exception e) {
            System.err.println("数据库写入失败");
            e.printStackTrace();
        }

        // 添加广播逻辑
        try {
            for (Session s : session.getOpenSessions()) {
                if (s.isOpen()) {
                    s.getBasicRemote().sendText(message);
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    // 其他回调方法...
}